﻿using MesBSW.DAL.MesDB;
using MesBSW.DAL.MesDTO;
using MesBSW.Tools;
using MesBSW.View;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MesBSW.BLL.Mes
{
    /// <summary>
    /// 用于处理站点和状态的业务逻辑
    /// </summary>
    public class SiteControler : BaseControler
    {
        /// <summary>
        /// 查询所有工单状态
        /// </summary>
        /// <returns></returns>
        public List<StatusInfo> SearchAllProdStatus()
        {
            using (MesDB ctx = new MesDB())
            {
                var query = from a in ctx.StatusTypes
                            join b in ctx.StatusInfos on a.ID equals b.StypeID into res
                            from ab in res.DefaultIfEmpty()
                            where a.StypeName == "工单状态"
                            select ab;
                if (query != null && query.Count() > 0)
                {
                    return query.ToList();
                }
                else
                { 
                    return null; 
                }
            }
        }

        /// <summary>
        /// 查询所有站点信息
        /// </summary>
        /// <returns></returns>
        public List<SiteInfo> SearchAllStieInfo()
        {
            List<SiteInfo> siteList = new List<SiteInfo>();
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.SiteInfos.OrderBy(s => s.SiteCode);
                if (query != null)
                {
                    siteList = query.ToList();
                }
            }
            return siteList;
        }

        /// <summary>
        /// 查询所有有子站点的站点
        /// </summary>
        /// <returns></returns>
        public List<SiteInfo> SearchNotFinalStieInfo()
        {
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.SiteInfos.Where(s => s.IsFinal != 1&&s.ParentID==0);
                if (query != null)
                {
                    return query.ToList();
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 通过父站点ID查询有相同父站点的子站点明细
        /// </summary>
        /// <param name="parentID">父站点ID</param>
        /// <returns></returns>
        public List<SiteInfo> SearchSiteInfoByParentID(int parentID)
        {
            using (MesDB ctx = new MesDB())
            {
                if (parentID > 0)
                {
                    List<SiteInfo> tmpList = new List<SiteInfo>();
                    var query = ctx.SiteInfos.Where(s => s.ParentID == parentID);
                    if (query != null)
                    {
                        tmpList = query.ToList();
                    }
                    return tmpList;
                }
                else
                {
                    return this.SearchAllStieInfo();
                }
            }
        }

        /// <summary>
        /// 新增站点信息
        /// </summary>
        /// <param name="siteBean">站点信息</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public int InsertSiteInfo(SiteInfo siteBean)
        {
            int count = 0;
            if (siteBean != null)
            {
                using (MesDB ctx = new MesDB())
                {
                    var query = ctx.SiteInfos.Where(s => s.SiteCode == siteBean.SiteCode || s.SiteName == siteBean.SiteName);
                    if (query != null && query.Count() > 0)
                    {
                        throw new Exception("站点代号：" + siteBean.SiteCode + "\r\n" + "或者" + "\r\n" + "站点名称：" + siteBean.SiteName + "\r\n" + "已经存在，新增失败！");
                    }
                    else if (this.IsExistsBeginOrEndPoint(siteBean) == true)
                    {
                        throw new Exception("父站点内不能有多个计算有效时间的" + (siteBean.CalPoint.Equals("B") ? "开始点" : "结束点") + "!");
                    }
                    else
                    {
                        siteBean.CreateDate = DateTime.Now;
                        siteBean.CreateUser = MainFrm.LoginUser.user_name;
                        ctx.SiteInfos.Add(siteBean);
                        count = ctx.SaveChanges();
                        return count;
                    }
                }
            }
            else
            {
                throw new Exception("没有任何可以保存的站点信息！");
            }
        }

        /// <summary>
        /// 保证父站点内，只有一个的有效时间的开始计算点或结束计算点
        /// </summary>
        /// <param name="siteInfo"></param>
        /// <returns></returns>
        public Boolean IsExistsBeginOrEndPoint(SiteInfo siteInfo)
        {
            Boolean isEx = false;
            using (MesDB ctx = new MesDB())
            {
                if (siteInfo.CalPoint != null)
                {
                    if (siteInfo.CalPoint.Equals("B") || siteInfo.CalPoint.Equals("E"))
                    {
                        var query = ctx.SiteInfos.Where(s => s.ParentID == siteInfo.ParentID && s.CalPoint.Equals(siteInfo.CalPoint));
                        if (query != null && query.Count() > 0)
                        {
                            isEx = true;
                        }
                    }
                }
            }
            return isEx;
        }

        /// <summary>
        /// 更新站点信息
        /// </summary>
        /// <param name="siteBean"></param>
        /// <param name="beforeStr"></param>
        /// <param name="afterStr"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public int UpdateSiteInfo(SiteInfo siteBean,string beforeStr,string afterStr)
        {
            int count = 0;
            if (siteBean != null)
            {
                MesLog logBean = new MesLog();
                logBean.ID = 0;
                logBean.TableName = "site_info";
                logBean.TableID = siteBean.ID;
                logBean.BeforeData = beforeStr;
                logBean.AfterData = afterStr;
                logBean.ChangeType = "update";
                logBean.ChangeDate = DateTime.Now;
                logBean.ChangeUser = MainFrm.LoginUser.user_name;

                using (MesDB ctx = new MesDB())
                {
                    ctx.SiteInfos.Attach(siteBean);
                    ctx.Entry<SiteInfo>(siteBean).State = System.Data.Entity.EntityState.Modified;

                    ctx.MesLogs.Add(logBean);

                    count = ctx.SaveChanges();
                    return count;
                }
            }
            else
            {
                throw new Exception("没有任何可以保存的站点信息！");
            }
        }

        /// <summary>
        /// 新增站点组别
        /// </summary>
        /// <param name="groupBean"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public int InsertSiteGroup(SiteGroup groupBean)
        {
            int count = 0;
            if (groupBean != null)
            {
                using (MesDB ctx = new MesDB())
                {
                    var query = ctx.SiteGroups.Where(g => g.GroupCode == groupBean.GroupCode || g.GroupName == groupBean.GroupName);
                    if (query != null && query.Count() > 0)
                    {
                        throw new Exception("组别代号：" + groupBean.GroupCode + "\r\n" + "或者" + "\r\n" + "组别名称：" + groupBean.GroupName + "\r\n" + "已经存在，新增失败！");
                    }
                    else
                    {
                        groupBean.CreateUser = MainFrm.LoginUser.user_name;
                        groupBean.CreateDate = DateTime.Now;
                        ctx.SiteGroups.Add(groupBean);
                        count = ctx.SaveChanges();
                        return count;
                    }
                }
            }
            else
            {
                throw new Exception("没有任何可以保存的站点组别信息！");
            }
        }


        /// <summary>
        /// 更新站点信息
        /// </summary>
        /// <param name="groupBean">站点组别</param>
        /// <param name="beforeStr">修改前内容，用于生成日志</param>
        /// <param name="afterStr">修改后内容，用于生成日志</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public int UpdateSiteGroup(SiteGroup groupBean, string beforeStr,string afterStr)
        {
            int count = 0;
            if (groupBean != null)
            {
                MesLog logBean = new MesLog();
                logBean.ID = 0;
                logBean.TableName = "site_group";
                logBean.TableID = groupBean.ID;
                logBean.BeforeData = beforeStr;
                logBean.AfterData = afterStr;
                logBean.ChangeType = "update";
                logBean.ChangeDate = DateTime.Now;
                logBean.ChangeUser = MainFrm.LoginUser.user_name;

                using (MesDB ctx = new MesDB())
                {
                    ctx.SiteGroups.Attach(groupBean);
                    ctx.Entry<SiteGroup>(groupBean).State = System.Data.Entity.EntityState.Modified;

                    ctx.MesLogs.Add(logBean);

                    count = ctx.SaveChanges();
                    return count;
                }
            }
            else
            {
                throw new Exception("没有任何可以保存的站点组别信息！");
            }
        }



        public List<SiteGroupDTO> SearchAllSiteGroup()
        {
            List<SiteGroupDTO> resList = new List<SiteGroupDTO>();
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.SiteGroups;
                if (query != null && query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        SiteGroupDTO dto = new SiteGroupDTO();
                        EntityTools.CopyEntity(item, ref dto);
                        var detailQuery = from a in ctx.SiteInfoGroups
                                          join b in ctx.SiteInfos on a.SiteID equals b.ID into res
                                          from ab in res.DefaultIfEmpty()
                                          where a.GroupID == dto.ID
                                          orderby a.Sort
                                          select new { A = a, AB = ab };
                        if (detailQuery != null && detailQuery.Count() > 0)
                        {
                            dto.SiteInfoList = new List<SiteInfoGroupDTO>();
                            foreach (var detail in detailQuery)
                            {
                                SiteInfoGroupDTO siteInfoGroupDTO = new SiteInfoGroupDTO();
                                EntityTools.CopyEntity(detail.A, ref siteInfoGroupDTO);
                                siteInfoGroupDTO.SiteInfo = detail.AB;
                                dto.SiteInfoList.Add(siteInfoGroupDTO); 
                            }
                        }
                        resList.Add(dto);
                    }
                }
            }
            return resList;
        }


        public int SaveSiteInfoGroup(SiteGroupDTO groupBean)
        {
            int count = 0;
            if (groupBean != null)
            {
                int tmpGroupID = groupBean.ID;
                string beforeStr = "";
                string afterStr = "";
                DateTime tmpDay = this.GetCurrDateTime();
                using (MesDB ctx = new MesDB())
                {
                    var headQuery = ctx.SiteGroups.Where(g => g.ID == tmpGroupID);
                    if (headQuery != null && headQuery.Count() > 0)
                    {
                        SiteGroup headBean = headQuery.First();
                        beforeStr = EntityTools.GetPropNameAndValue(headBean);
                        headBean.GroupName = groupBean.GroupName;
                        headBean.IsDel = groupBean.IsDel;
                        afterStr = EntityTools.GetPropNameAndValue(headBean);
                        if (beforeStr.Equals(afterStr) == false)
                        {
                            MesLog tmpLog = this.InitMesLog("site_group", headBean.ID, beforeStr, afterStr, "Update", MainFrm.LoginUser.user_name, tmpDay);
                            ctx.MesLogs.Add(tmpLog);


                        }
                    }

                    var detailQuery = ctx.SiteInfoGroups.Where(s => s.GroupID == tmpGroupID);
                    if (detailQuery != null && detailQuery.Count() > 0)
                    {
                        foreach (var item in detailQuery)
                        {
                            MesLog tmpLog = this.InitMesLog("site_info_group", item.ID, EntityTools.GetPropNameAndValue(item), "", "Delete", MainFrm.LoginUser.user_name, tmpDay);
                            ctx.MesLogs.Add(tmpLog);

                            ctx.SiteInfoGroups.Remove(item);
                        }
                    }

                    foreach (var item in groupBean.SiteInfoList)
                    {
                        SiteInfoGroup tmpBean = new SiteInfoGroup();
                        EntityTools.CopyEntity(item,ref tmpBean);
                        tmpBean.ID = 0;
                        tmpBean.CreateDate = tmpDay;
                        tmpBean.CreateUser = MainFrm.LoginUser.user_name;
                        ctx.SiteInfoGroups.Add(tmpBean);
                    }
                    count += ctx.SaveChanges();
                }
                return count;
            }
            else
            {
                throw new Exception("没有任何可以保存的站点信息！");
            }
        }


        public List<StatusTypeDTO> SearchAllStatesType()
        {
            List<StatusTypeDTO> resList = new List<StatusTypeDTO>();
            using (MesDB ctx = new MesDB())
            {
                var typeQuery = ctx.StatusTypes;
                var infoQuery = ctx.StatusInfos;

                if (typeQuery != null && typeQuery.Count() > 0)
                {
                    foreach (var type in typeQuery)
                    {
                        StatusTypeDTO typeDto = new StatusTypeDTO();
                        EntityTools.CopyEntity<StatusType,StatusTypeDTO>(type,ref typeDto);
                        if (infoQuery != null && infoQuery.Count() > 0)
                        {
                            var tmpQuery = infoQuery.Where(i => i.StypeID == type.ID);
                            if (tmpQuery != null && tmpQuery.Count() > 0)
                            {
                                typeDto.StatusInfoList = new List<StatusInfo>();
                                typeDto.StatusInfoList.AddRange(tmpQuery);
                            }
                        }
                        resList.Add(typeDto);
                    }
                }
            }
            return resList;
        }


        /// <summary>
        /// 判断状态是否已经存在
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public Boolean IsExistsStatusInfo(StatusInfo status)
        {
            Boolean isEx = false;
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.StatusInfos.Where(s => s.StatusCode.Equals(status.StatusCode) || s.StatusValue.Equals(status.StatusValue));
                if (query != null && query.Count() > 0)
                {
                    isEx = true;   
                }
            }
            return isEx;
        }

        /// <summary>
        /// 新增状态
        /// </summary>
        /// <param name="status">状态信息</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public int InsertStatusInfo(StatusInfo status)
        {
            using (MesDB ctx = new MesDB())
            {
                if (status != null)
                {
                    if (this.IsExistsStatusInfo(status) == false)
                    {
                        status.CreateDate = DateTime.Now;
                        status.CreateUser = MainFrm.LoginUser.user_name;
                        ctx.StatusInfos.Add(status);
                        int count = ctx.SaveChanges();
                        return count;
                    }
                    else
                    {
                        throw new Exception("新增的状态已经存在，中止保存！");
                    }
                }
                else
                {
                    throw new Exception("传入的状态为空，无法保存！");
                }
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="status">状态信息</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public int UpdateStatusInfo(StatusInfo status)
        {
            if (status != null)
            {
                using (MesDB ctx = new MesDB())
                {
                    ctx.StatusInfos.Attach(status);
                    ctx.Entry(status).State = System.Data.Entity.EntityState.Modified;
                    int count = ctx.SaveChanges();
                    return count;
                }
            }
            else
            {
                throw new Exception("传入的状态为空，无法保存！");
            }
        }


        /// <summary>
        /// 根据用户ID查询当前用户可以操作的站点
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public List<UserSite> SearchSiteInfoForUserID(int userid)
        {
            List<UserSite> resList = new List<UserSite>();
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.UserSite.Where(s => s.UserID == userid);
                if (query != null)
                {
                    resList.AddRange(query);
                }
            }
            return resList;
        }


        /// <summary>
        /// 新增用户站点分配信息
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="siteList"></param>
        /// <returns></returns>
        public int SaveUserSite(int userID,List<UserSite> siteList)
        {
            int count = 0;
            DateTime tmpDay = this.GetCurrDateTime();
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.UserSite.Where(s => s.UserID == userID);
                if (query != null && query.Count() > 0)
                {
                    ctx.Set<UserSite>().RemoveRange(query);
                }

                if (siteList != null && siteList.Count > 0)
                {
                    foreach (var item in siteList)
                    {
                        item.CreateDate = tmpDay;
                        item.CreateUser = MainFrm.LoginUser.user_name;
                        ctx.UserSite.Add(item);
                    }
                }

                count = ctx.SaveChanges();
            }
            return count;
        }
    }
}
